package com.t249.bdqn.renting.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.t249.bdqn.renting.dao.*;
import com.t249.bdqn.renting.entity.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/retPersonage")
public class PersonageController {

    Integer sid = 1;

    @Resource
    private RetAddressDao retAddressDao;

    @Resource
    private RetRegionDao retRegionDao;

    @Resource
    private RetRentalInformationDao retRentalInformationDao;

    @Resource
    private RetPropertiesDao retPropertiesDao;

    @Resource
    private RetImgDao retImgDao;

    @Resource
    private RetHuxingDao retHuxingDao;;

    @Resource
    private RetPaymentDao paymentDao;

    @Resource
    private RetHousingResourcesDao retHousingResourcesDao;

    @Resource
    private SysBookingDao sysBookingDao;

    @Resource
    private RetCollectionDao retCollectionDao;

    @Resource
    private RetMessageDao retMessageDao;


    //个人中心
    @RequestMapping(value = "/personage")
    public Object personage(Model model, RetAddress retAddress){
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        if(retAddress.getId() != null){
            //根据id获取相对应的城市名称
            sid = retAddress.getId();
            RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",retAddress.getId()));
            //根据id获取相对应的区域
            List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",retAddress.getId()));
            //根据id来查询相关城市里的房源信息
            model.addAttribute("retRegionList",retRegionList);
            model.addAttribute("cityName",retAddressId.getCityName());
            model.addAttribute("cityId",retAddressId.getId());
        }else{
            sid = 1;
            //没有id就默认为深圳
            List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",1));
            //没有id就默认为显示深圳的房源
            model.addAttribute("retRegionList",retRegionList);
            model.addAttribute("cityName","深圳");
            model.addAttribute("cityId",sid);
        }
        model.addAttribute("retAddressList",retAddressList);
        return "personage/Personage.html";
    }

    //设置密码
    @RequestMapping(value = "/modifyPwd")
    public Object modifyPwd(Model model){
        //没有id就默认为深圳
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        //没有id就默认为显示深圳的房源
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        return "personage/Password.html";
    }

    //系统消息
    @RequestMapping(value = "/message")
    public Object message(Model model){
        //没有id就默认为深圳
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        List<Map<String,Object>> mapList = retMessageDao.chaxun(sid.toString());
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        model.addAttribute("mapList",mapList);
        return "personage/Message.html";
    }

    //我的收藏
    @RequestMapping(value = "/favorite")
    public Object favorite(Model model){
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        List<Map<String,Object>> mapList = retCollectionDao.souchang(sid.toString());
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        model.addAttribute("mapList",mapList);
        return "personage/Favorite.html";
    }

    @RequestMapping(value = "/deleteZhuantai")
    @ResponseBody
    public String deleteZhuantai(Integer id){
        System.out.println(id);
        String fanhui = null;
        int count = retCollectionDao.xuigaiZuantai(1,id);
        if(count >0 ){
            fanhui  = "0";
        }else{
            fanhui = "1";
        }
        return JSONArray.toJSONString(fanhui);
    }

    //预定管理
    @RequestMapping(value = "/appointment")
    public String appointment(Model model,HttpServletRequest request){
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        String userId = request.getSession().getAttribute("userId").toString();
        List<Map<String,Object>> mapList = retRentalInformationDao.shujuchaxun(sid,userId);
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        model.addAttribute("retAppointmentList",mapList);
        return "personage/Appointment.html";
    }

    //取消
    @RequestMapping(value = "/aptQuxiao")
    @ResponseBody
    public String appointment(String id,String quxiaoYuanyin){
        String fanhui="";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        int count=sysBookingDao.XuigaiZhuantai(df.format(new Date()),"3",quxiaoYuanyin,id);
        if(count>0){
            fanhui="0";
        }else{
            fanhui="1";
        }
        return JSONArray.toJSONString(fanhui);
    }

    //变更
    @RequestMapping(value = "/biangen")
    @ResponseBody
    public String biangen(String id,String appointmentTime){
        String fanhui="";
        int count=sysBookingDao.XuigaiBiangen(appointmentTime,id);
        if(count>0){
            fanhui="0";
        }else{
            fanhui="1";
        }
        return JSONArray.toJSONString(fanhui);
    }

    //出租房源首页
    @RequestMapping(value = "/apt/index")
    public Object aptIndex(Model model,HttpServletRequest request){
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        List<Map<String,Object>> retRentalInformationList = retRentalInformationDao.ChengshiSelect1(sid,request.getSession().getAttribute("userId").toString());
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        model.addAttribute("retRentalInformationList",retRentalInformationList);
        return "personage/apt/index.html";
    }

    //发布房源
    @RequestMapping(value = "/apt/new")
    public String aptNew(Model model){
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        //无条件情况下获取所以的城市名称
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        return "personage/apt/new.html";
    }

    //读取需要编辑房源信息
    @RequestMapping(value = "/apt/edit")
    public Object aptEdit(Model model,Integer id){
        List<RetRegion> retRegionList = retRegionDao.selectList(new QueryWrapper<RetRegion>().eq("address_Id",sid));
        RetAddress retAddressId = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",sid));
        List<RetHuxing> retHuxingList = retHuxingDao.selectList(null);
        List<RetAddress> retAddressList = retAddressDao.selectList(null);
        List<Map<String,Object>> retRentalInformationList = retRentalInformationDao.ChengshiSelect2(id);
        List<RetProperties> retPropertiesList = retPropertiesDao.selectList(null);
        List<RetPayment> retPaymentList = paymentDao.selectList(null);
        List<RetHousingResources> retHousingResourcesList = retHousingResourcesDao.selectList(null);
        model.addAttribute("retAddressList",retAddressList);
        model.addAttribute("retRegionList",retRegionList);
        model.addAttribute("cityName",retAddressId.getCityName());
        model.addAttribute("cityId",retAddressId.getId());
        model.addAttribute("retRentalInformationList",retRentalInformationList);
        model.addAttribute("retHuxingList",retHuxingList);
        model.addAttribute("retPropertiesList",retPropertiesList);
        model.addAttribute("retPaymentList",retPaymentList);
        model.addAttribute("retHousingList",retHousingResourcesList);
        return "personage/apt/edit.html";
    }

    //编辑房源
    @RequestMapping(value = "/apt/edit1")
    @ResponseBody
    public String edit1(String money,String paymentId,String housingId,String retDescribe,String retJiaoton,String retId){
        String fanhui="";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        int count = retRentalInformationDao.updatetijiao(money,paymentId,housingId,retDescribe,retJiaoton,df.format(new Date()),retId);
        if(count>0){
            fanhui="0";
        }else{
            fanhui="1";
        }
        return JSONArray.toJSONString(fanhui);
    }

    //根据id显示相应的乡镇
    @RequestMapping(value = "/propertiesId")
    public String propertiesId(Integer id,Model model){
        List<RetProperties> retPropertiesList =retPropertiesDao.selectList(new QueryWrapper<RetProperties>().eq("region_id",id));
        model.addAttribute("retPropertiesList",retPropertiesList);
        return "personage/apt/new::chuang";
    }

    //发布房源（新增）
    @RequestMapping(value = "/informationadd",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject singleFileUpload(@RequestParam("file")MultipartFile[] file){
        RetImg retImg = new RetImg();
        JSONObject jsonObject = new JSONObject();
        StringBuilder stringBuilder1 = new StringBuilder();
        if(file.length > 0){
            String luj = "/img/pc/client/home/quanbu/";
            int max = retRentalInformationDao.MaxId();
            int count = retRentalInformationDao.updateFanyuan(stringBuilder1.append(luj).append(file[0].getOriginalFilename()).toString(),max);
            if(count > 0 ){
                for (MultipartFile multipartFile : file) {
                    if (multipartFile.isEmpty()) {
                        jsonObject.put("result", -1);
                        return jsonObject;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    StringBuilder stringBuilder = new StringBuilder();
                    File fileDir = new File("src/main/resources/static/img/pc/client/home/quanbu/");
                    String path = fileDir.getAbsolutePath();
                    if(!fileDir.exists()){
                        fileDir.mkdir();
                    }
                    try {
                        retImg.setRetRentalId(max);
                        retImg.setImgPicture(stringBuilder.append(luj).append(fileName).toString());
                        int shu = retImgDao.insert(retImg);
                        if(shu > 0){
                            multipartFile.transferTo(new File(path, fileName));
                            jsonObject.put("result", 1);
                            jsonObject.put("message", "ok");
                            jsonObject.put("url", stringBuilder.append(luj).append(fileName).toString());
                        }else{
                            jsonObject.put("result", -1);
                            return jsonObject;
                        }
                    } catch (Exception e) {
                        jsonObject.put("result", 0);
                        e.printStackTrace();
                    }
                }
            }else{
                jsonObject.put("result", -1);
                return jsonObject;
            }
        }else{
            jsonObject.put("result", -1);
            return jsonObject;
        }
        return jsonObject;
    }

    @RequestMapping(value = "/fanyuanAdd")
    @ResponseBody
    public String fanyuanAdd(RetRentalInformation retRentalInformation) throws IOException{
        String fanhui = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Object[] o = getCoordinate(chengshi(retRentalInformation.getAddressId())+"市"+quyu(retRentalInformation.getRegionId())+"区"+xiangzheng(retRentalInformation.getRetPropertiesId()+retRentalInformation.getLeaseOut()));
        retRentalInformation.setRetLng(o[0].toString());
        retRentalInformation.setRetLat(o[1].toString());
        retRentalInformation.setRetTypeId("11");
        retRentalInformation.setShijiang(df.format(new Date()));
        int count = retRentalInformationDao.insert(retRentalInformation);
        if(count > 0){
            fanhui = "0";
        }else{
            fanhui = "1";
        }
        return JSONArray.toJSONString(fanhui);
    }


    @ResponseBody
    public String chengshi(String addressId){
        RetAddress address = retAddressDao.selectOne(new QueryWrapper<RetAddress>().eq("id",addressId));
        return JSONArray.toJSONString(address.getCityName());
    }

    @ResponseBody
    public String quyu(String regionId){
        RetRegion retRegion = retRegionDao.selectOne(new QueryWrapper<RetRegion>().eq("id",regionId));
        return JSONArray.toJSONString(retRegion.getCityName());
    }

    @ResponseBody
    public String xiangzheng(String retPropertiesId){
        RetProperties retProperties = retPropertiesDao.selectOne(new QueryWrapper<RetProperties>().eq("id",retPropertiesId));
        return JSONArray.toJSONString(retProperties.getProperties());
    }




    //经纬度查询方法
    public Object[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "f247cdb592eb43ebac6ccd27f796e2d2";
        String url = String .format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                int count = 1;
                while((data= br.readLine())!=null){
                    if(count==5){
                        lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                        count++;
                    }else if(count==6){
                        lat = data.substring(data.indexOf(":")+1);//纬度
                        count++;
                    }else{
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return new Object[]{lng,lat};
    }
}
